//
//  ViewController.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/10/27.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"
#import <WebKit/WebKit.h>

#define KFundList @"/public/product/get-fund-type-performance-chart"

@interface ViewController ()<WKUIDelegate, WKNavigationDelegate>

@property (nonatomic, weak) WKWebView *webView;
@property (nonatomic, strong) NSMutableArray *rateData;
@property (nonatomic, strong) NSMutableArray *timeData;

@end

@implementation ViewController

- (NSMutableArray *)timeData{
    if (!_timeData) {
        self.timeData = [NSMutableArray array];
        
    }
    return _timeData;
}

- (NSMutableArray *)rateData{
    if (!_rateData) {
        self.rateData = [NSMutableArray array];
        
    }
    return _rateData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
//    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
//    dict[@"X-API-KEY"] = KApikey;
//    dict[@"X-API-SIGNATURE"] = KPrivateKey;
//    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;
//    dict[@"X-API-TIMESTAMP"] = [NSString stringWithFormat:@"%f", interval];
//    dict[@"X_API_VERSION"] = @"1.0";
//    
//    AFHTTPSessionManager *manager =  [AFHTTPSessionManager manager];
//    manager.requestSerializer.timeoutInterval = 30;
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//   
//    [manager GET:@"https://43.247.70.232/public/product/portfolio/find-recommended-product-portfolio-list" parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
    
    [self getData];
    [self test];
}

- (void)getData{
    
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"fundType"] = @"MM";
    
    paramets[@"period"] = @"0";
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KFundList};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            //            [SVProgressHUD showSuccessWithStatus:result[@"message"]];
            NSArray *dataArray = result[@"data"];
            for (int i = 0; i < dataArray.count; i++) {
                NSDictionary *dict = dataArray[i];
                NSString *time = [self getDateStringWith:dict[@"navDate"]];
                [self.timeData addObject:time];
                [self.rateData addObject:dict[@"performance"]];
            }
            
        }else{
           
        }
        
    } failure:^(NSError *errer) {
        
        
    }];
}

- (NSString *)getDateStringWith:(NSNumber *)ti{
    
    NSNumber *navDate = ti;
    NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
    [stampFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:[navDate doubleValue] / 1000];
    NSString *dateString = [stampFormatter stringFromDate:stampDate2];
    return dateString;
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *finalStr = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return finalStr;
}

- (void)test{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    CGRect rect = CGRectMake(0, 20, self.view.frame.size.width, 150);
    WKWebView *webview = [[WKWebView alloc] initWithFrame:rect configuration:config];
    webview.navigationDelegate = self;
    webview.scrollView.scrollEnabled = YES;
    webview.UIDelegate = self;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"echarts" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:path];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];
    
//    webview loadFileURL:<#(nonnull NSURL *)#> allowingReadAccessToURL:<#(nonnull NSURL *)#>
    
    [self.view addSubview:webview];
    _webView = webview;
}

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}

-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    [self.webView evaluateJavaScript:@"initD()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        //TODO
    }];
    NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
    dataDict[@"xData"] = self.timeData;
    dataDict[@"yData"] = [NSArray arrayWithObjects:self.rateData, self.rateData, nil];
    dataDict[@"legend"] = [NSArray arrayWithObjects:@"1", @"2", nil];
    dataDict[@"color"] = [NSArray arrayWithObjects:@"green", @"green", nil];
    NSString *str = [self dictionaryToJson:dataDict];
    NSString *finalStr = [NSString stringWithFormat:@"initChart(%@)", str];
    [self.webView evaluateJavaScript:finalStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        //TODO
    }];
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    //    NSLog(@"js弹框了");
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"JS-Coder" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alertView addAction:[UIAlertAction actionWithTitle:@"Sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //一定要调用下这个block
        //API说明：The completion handler to call after the alert panel has been dismissed
        completionHandler();
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
    
}



- (void)handleFactorialCalculateWithNumber:(NSDictionary *)number
{
    
    
//    NSArray *array = [NSArray arrayWithObjects:dataDict, nil];
//    [self.context[@"showResult"] callWithArguments:array];
}

@end
